import re
import time
from abc import ABC, abstractmethod

import xlrd
import tqdm
import copy
import settings
from credit_voice_service.dialogue.cache import constants
from credit_voice_service.dialogue.cache.constants import LABEL_LLM, LABEL_D
from credit_voice_service.dialogue.util.operate_excel import OperateExcel
from openpyxl import load_workbook, Workbook
from treelib import Node, Tree
from credit_voice_service.settings import log

operateExcel = OperateExcel()


# 提前大流程名
def withdrawFlowName(content):
    if content is None or content == "":
        return ""
    pattern = r'\【(.*?)\】'  # 匹配[]中的内容
    content = content.replace("【faq答案】", "").replace("【FAQ答案】", "")
    match = re.search(pattern, content)
    if match:
        settings.log.info("匹配内容:{}".format(match.group(1)))
        return match.group(1)
    return ""


# 获取上一轮编号
def preRoundOrder(reverseOrder):
    reverseOrder = str(reverseOrder)
    if "." not in reverseOrder:
        return ""
    last_dot_index = reverseOrder.rfind(".")
    order = reverseOrder[:last_dot_index]

    letters = re.findall(r'\(([a-zA-Z]=\d).*?\)', reverseOrder)
    if letters is not None and len(letters) > 0:
        letter = letters[len(letters) - 1]
        if "=" in letter:
            kw = letter.split("=")
            order = order.replace(kw[0], kw[1])
    return order


# 获取上一轮编号
def curRoundOrder(reverseOrder):
    reverseOrder = str(reverseOrder)
    if "." not in reverseOrder:
        return ""
    match_num = re.search("(.*?\.\d+)", reverseOrder)
    if match_num:
        order = match_num.group(1)
    else:
        order = reverseOrder
    return order


class BuildDataInterface(ABC):
    @abstractmethod
    def buildData(self):
        pass


# 现有流程
class BuildDataByFileTwo(BuildDataInterface):
    def __init__(self):
        self.operateExcel = OperateExcel()

    def buildData(self):
        readBook = xlrd.open_workbook(settings.dialogue_file_path)
        sheetFaq = readBook.sheet_by_name(settings.dialogue_file_sheet)
        sheetVersionList = []
        # 外部跳转
        out_jump = {"核身-在忙": "在忙", "核产环节-不需要": "是的,不需要",
                    "开场-在忙": "是的,在忙", "开场-在忙-有原因": "是的,在忙-有原因",
                    "开场-后续操作": "是的,有空再操作",
                    "开场-发短信": "是的,发短信", "开场-怎么加": "是的,加不了",
                    "子流程引导加微环节-在忙": "是的,是的,在忙", "子流程引导加微环节-不需要": "是的,是的,不需要"}
        in_jump = {}
        pre_query = ""
        pre_round = 1
        index_start = 2
        index_end = sheetFaq.nrows
        for i in range(index_start, index_end):
            reverseOrder = sheetFaq.cell(i, LABEL_D["standard_order"]).value
            if reverseOrder == 1.0:
                reverseOrder = 1
            attitude = sheetFaq.cell(i, LABEL_D["standard_attitude"]).value.strip()
            # todo 命中FAQ 可以修改
            if 'FAQ' in attitude:
                attitude = "关于产品"
            elif '否定' in attitude:
                attitude = '不是'
            elif '静音' in attitude:
                attitude = "@@quiet@@"
            number = sheetFaq.cell(i, LABEL_D["standard_number"]).value
            label = sheetFaq.cell(i, LABEL_D["standard_label"]).value
            content = sheetFaq.cell(i, LABEL_D["standard_content"]).value
            action = sheetFaq.cell(i, LABEL_D["action"]).value
            merged = sheetFaq.merged_cells
            label_node = self.operateExcel.get_cell_type(i, constants.FLOW_NAME, merged, sheetFaq)

            # 构建请求的话术
            cur_round = len(str(reverseOrder).split("."))
            # 处理顺序
            pre_order = preRoundOrder(reverseOrder)
            cur_order = curRoundOrder(reverseOrder)
            log.info("寻找上一轮的请求话术:{}".format(pre_order))
            if pre_round != cur_round and pre_order in in_jump:
                if pre_query == "":
                    pre_query = in_jump[pre_order]
                    # pre_query = pre_question_single
                else:
                    pre_query = "{},{}".format(pre_query, in_jump[pre_order])
                    # pre_query = "{},{}".format(pre_query, pre_question_single)
                pre_round = cur_round

            cur_content = ""
            if str(reverseOrder) == "1" and i == index_start:
                self.operateExcel.define_excel_format_test(label_node, attitude, "", number, content, sheetVersionList)
            elif str(reverseOrder) == "1" and i != index_start:
                # 1.0 获取外部的使用
                if label_node in out_jump:
                    pre_query = out_jump[str(label_node)]
                    del out_jump[str(label_node)]
                # 1.1 更新已经运行的跳转
                for version in sheetVersionList:
                    if version["录音编号"] != '':
                        continue
                    cur_content = version["场景话术"]
                    cur_query = version["请求话术"]
                    if label_node in cur_content and attitude in cur_content:
                        version["录音编号"] = number
                        cur_query = cur_query
                    elif label_node in cur_content and attitude == "首句":
                        version["录音编号"] = number
                        cur_query = cur_query
                # 1.3 清空子BOT内部存储信息
                in_jump = {}
                pre_question_single = ""
            else:
                # 扭转跳转中有多个的，处理重复
                attitudeList = attitude.split("\n")
                for attitude_one in attitudeList:
                    cur_content = attitude_one
                    if pre_query != "":
                        cur_content = "{},{}".format(pre_query, attitude_one)
                    self.operateExcel.define_excel_format_test(label_node, attitude_one, cur_content,
                                                               number, content, sheetVersionList)

                # 不是挂机的，记录下当前对话
                if number != '' and constants.ACTION_END not in action:
                    pre_round = cur_round
                    # pre_question_single = attitude.split("\n")[0]
                    if cur_order != "":
                        in_jump[cur_order] = attitude.split("\n")[0]
                        pre_question_single = ""

                # 跳转流程
                if number == '' and constants.ACTION_END not in action:
                    # 1.1 记录跳转的最后的路径
                    flowName = withdrawFlowName(content)
                    if flowName != "" and "不需要返回" not in cur_content:
                        if flowName not in out_jump:
                            out_jump[str(flowName)] = cur_content
                        elif flowName in out_jump and len(out_jump.get(flowName)) >= len(cur_content):
                            out_jump[str(flowName)] = cur_content
                    log.info("cur_content:{}".format(cur_content))

        path = "../excel/workspace_test.xlsx"
        print(path)
        operateExcel.write_excel_info(sheetVersionList, path)
        return sheetVersionList


# 现有流程
class BuildDataByFile(BuildDataInterface):
    def __init__(self):
        self.operateExcel = OperateExcel()

    def buildData(self):
        # operateExcel = OperateExcel()
        readBook = xlrd.open_workbook(settings.dialogue_file_path)
        sheetFaq = readBook.sheet_by_name(settings.dialogue_file_sheet)
        sheetVersionList = []
        faq_question = ""
        pre_question = ""
        pre_round = 1
        index_start = 2
        index_end = sheetFaq.nrows
        for i in range(index_start, index_end):
            reverseOrder = sheetFaq.cell(i, constants.FLOW_ORDER).value
            if reverseOrder == 1.0:
                reverseOrder = 1
            attitude = sheetFaq.cell(i, constants.FLOW_ATTITUDE).value
            # todo 命中FAQ 可以修改
            if '命中FAQ' in attitude:
                attitude = "什么平台"
            elif '否定' in attitude:
                attitude = '不是'
            elif '静音' in attitude:
                attitude = "@@quiet@@"
            number = sheetFaq.cell(i, constants.FLOW_RECORD_NUMBER).value
            label = sheetFaq.cell(i, constants.FLOW_LABEL_USER).value
            content = sheetFaq.cell(i, constants.FLOW_WORDS).value
            action = sheetFaq.cell(i, constants.FLOW_LABEL_ACTION).value
            merged = sheetFaq.merged_cells
            label_node = self.operateExcel.get_cell_type(i, constants.FLOW_NAME, merged, sheetFaq)
            cur_round = len(str(reverseOrder).split("."))
            if pre_round != cur_round and pre_question != '':
                if faq_question == "":
                    faq_question = pre_question.replace("/n", "")
                else:
                    faq_question = "{},{}".format(faq_question, pre_question.replace("/n", ""))
                pre_round = cur_round
                pre_question = ""
            if reverseOrder == 1 and i == index_start:
                self.operateExcel.define_excel_format_test(label_node, attitude, "", number, content, sheetVersionList)
                cur_question = ""
            elif reverseOrder == 1 and i != index_start:
                for version in sheetVersionList:
                    if version["录音编号"] != '':
                        continue
                    faq_content = version["场景话术"]
                    faq_question = version["请求话术"]
                    if label_node in faq_content and "｜" in faq_content and attitude in faq_content:
                        version["录音编号"] = number
                        faq_question = faq_question
                    elif label_node in faq_content and "｜" in faq_content:
                        continue
                    elif label_node in faq_content:
                        version["录音编号"] = number
                        faq_question = faq_question
            else:
                if number != '' and constants.ACTION_END not in action:
                    pre_round = cur_round
                    pre_question = attitude
                content_temp = attitude
                if faq_question != "":
                    content_temp = "{},{}".format(faq_question, attitude)
                self.operateExcel.define_excel_format_test(label_node, attitude, content_temp, number, content, sheetVersionList)

        path = "../excel/workspace_test.xlsx"
        print(path)
        operateExcel.write_excel_info(sheetVersionList, path)
        return sheetVersionList


# 大模型的构造
class BuildDataByLLM(BuildDataInterface):
    def __init__(self):
        self.operateExcel = OperateExcel()

    def buildData(self):
        # operateExcel = OperateExcel()
        readBook = xlrd.open_workbook(settings.dialogue_file_path)
        sheetFaq = readBook.sheet_by_name(settings.dialogue_file_sheet)
        sheetVersionList = []
        faq_question = ""
        pre_question = ""
        pre_round = 1
        index_start = 2
        # index_start = 13
        index_end = sheetFaq.nrows
        for i in range(index_start, index_end):
            reverseOrder = sheetFaq.cell(i, constants.FLOW_ORDER).value
            if reverseOrder == 1.0:
                reverseOrder = 1
            attitude = sheetFaq.cell(i, constants.FLOW_ATTITUDE).value
            # todo 命中FAQ 可以修改
            if '命中FAQ' in attitude:
                attitude = "什么平台"
            elif '否定' in attitude:
                attitude = '不是'
            elif '静音' in attitude:
                attitude = "@@quiet@@"
            number = sheetFaq.cell(i, constants.FLOW_RECORD_NUMBER).value
            label = sheetFaq.cell(i, constants.FLOW_LABEL_USER).value
            content = sheetFaq.cell(i, constants.FLOW_WORDS).value
            action = sheetFaq.cell(i, LABEL_LLM["action"]).value
            merged = sheetFaq.merged_cells
            label_node = self.operateExcel.get_cell_type(i, constants.FLOW_NAME, merged, sheetFaq)
            cur_round = len(str(reverseOrder).split("."))
            if pre_round != cur_round and pre_question != '':
                if faq_question == "":
                    faq_question = pre_question.replace("/n", "")
                else:
                    faq_question = "{},{}".format(faq_question, pre_question.replace("/n", ""))
                pre_round = cur_round
                pre_question = ""
            if str(reverseOrder) == "1" and i == index_start:
                self.operateExcel.define_excel_format_test(label_node, attitude, "", number, content, sheetVersionList)
                cur_question = ""
            elif str(reverseOrder) == "1" and i != index_start:
                for version in sheetVersionList:
                    if version["录音编号"] != '':
                        continue
                    faq_content = version["场景话术"]
                    faq_question = version["请求话术"]
                    if label_node in faq_content and "｜" in faq_content and attitude in faq_content:
                        version["录音编号"] = number
                        faq_question = faq_question
                    elif label_node in faq_content and "｜" in faq_content:
                        continue
                    elif label_node in faq_content:
                        version["录音编号"] = number
                        faq_question = faq_question
            else:
                if number != '' and constants.ACTION_END not in action:
                    pre_round = cur_round
                    pre_question = attitude
                content_temp = attitude
                if faq_question != "":
                    content_temp = "{},{}".format(faq_question, attitude)
                self.operateExcel.define_excel_format_test(label_node, attitude, content_temp, number, content, sheetVersionList)

        path = "../excel/workspace_test.xlsx"
        print(path)
        operateExcel.write_excel_info(sheetVersionList, path)
        return sheetVersionList


# 大模型的构造
class BuildDataByLLM_copy(BuildDataInterface):
    def __init__(self):
        self.operateExcel = OperateExcel()

    def buildData(self):
        readBook = xlrd.open_workbook(settings.dialogue_file_path)
        sheetFaq = readBook.sheet_by_name(settings.dialogue_file_sheet)
        sheetVersionList = []
        # 外部跳转
        out_jump = {}
        in_jump = {}
        pre_question_single = ""
        pre_query = ""
        pre_round = 1
        index_start = 2
        # index_start = 13
        index_end = sheetFaq.nrows
        for i in range(index_start, index_end):
            reverseOrder = sheetFaq.cell(i, LABEL_LLM["standard_order"]).value
            if reverseOrder == 1.0:
                reverseOrder = 1
            attitude = sheetFaq.cell(i, LABEL_LLM["standard_attitude"]).value.strip()
            # todo 命中FAQ 可以修改
            if 'FAQ' in attitude:
                attitude = "什么平台"
            elif '否定' in attitude:
                attitude = '不是'
            elif '静音' in attitude:
                attitude = "@@quiet@@"
            number = sheetFaq.cell(i, LABEL_LLM["standard_number"]).value
            label = sheetFaq.cell(i, LABEL_LLM["standard_label"]).value
            content = sheetFaq.cell(i, LABEL_LLM["standard_content"]).value
            action = sheetFaq.cell(i, LABEL_LLM["action"]).value
            merged = sheetFaq.merged_cells
            label_node = self.operateExcel.get_cell_type(i, constants.FLOW_NAME, merged, sheetFaq)

            # 构建请求的话术
            cur_round = len(str(reverseOrder).split("."))
            # 处理顺序
            orderList = str(reverseOrder).split("\n")
            pre_order = ""
            cur_order = orderList[0]
            if orderList is not None and len(orderList) > 1:
                letters = re.findall('[a-zA-Z]', cur_order)
                last_letter = letters[len(letters)-1]
                letter_num = orderList[len(orderList)-1].strip()
                if last_letter in letter_num:
                    letter_num = letter_num.replace(last_letter, "").replace("=", "")
                    x = letter_num
                    if "," in letter_num:
                        x_list = letter_num.split(",")
                        x = x_list[len(x_list) - 1]
                    pre_order = cur_order.replace(last_letter, x)
                    pre_order = pre_order.rsplit('.', 1)[0]
                log.info("寻找上一轮的请求话术:{}".format(pre_order))
            # ------------------
            if pre_round != cur_round and pre_order in in_jump:
                if pre_query == "":
                    pre_query = in_jump[pre_order]
                    # pre_query = pre_question_single
                else:
                    pre_query = "{},{}".format(pre_query, in_jump[pre_order])
                    # pre_query = "{},{}".format(pre_query, pre_question_single)
                pre_round = cur_round

            cur_content = ""
            if str(reverseOrder) == "1" and i == index_start:
                self.operateExcel.define_excel_format_test(label_node, attitude, "", number, content, sheetVersionList)
            elif str(reverseOrder) == "1" and i != index_start:
                # 1.0 获取外部的使用
                if label_node in out_jump:
                    pre_query = out_jump[str(label_node)]
                    del out_jump[str(label_node)]
                # 1.1 更新已经运行的跳转
                for version in sheetVersionList:
                    if version["录音编号"] != '':
                        continue
                    cur_content = version["场景话术"]
                    cur_query = version["请求话术"]
                    if label_node in cur_content and attitude in cur_content:
                        version["录音编号"] = number
                        cur_query = cur_query
                    elif label_node in cur_content and attitude == "首句":
                        version["录音编号"] = number
                        cur_query = cur_query
                # 1.3 清空子BOT内部存储信息
                in_jump = {}
            else:
                # 扭转跳转中有多个的，处理重复
                attitudeList = attitude.split("\n")
                for attitude_one in attitudeList:
                    cur_content = attitude_one
                    if pre_query != "":
                        cur_content = "{},{}".format(pre_query, attitude_one)
                    self.operateExcel.define_excel_format_test(label_node, attitude_one, cur_content,
                                                               number, content, sheetVersionList)

                # 不是挂机的，记录下当前对话
                if number != '' and constants.ACTION_END not in action:
                    pre_round = cur_round
                    # pre_question_single = attitude.split("\n")[0]
                    if cur_order != "":
                        in_jump[cur_order] = attitude.split("\n")[0]

                # 跳转流程
                if number == '' and constants.ACTION_END not in action:
                    # 1.1 记录跳转的最后的路径
                    flowName = withdrawFlowName(content)
                    if flowName != "":
                        out_jump[str(flowName)] = cur_content
                    log.info("cur_content:{}".format(cur_content))

        path = "../excel/workspace_test.xlsx"
        print(path)
        operateExcel.write_excel_info(sheetVersionList, path)
        return sheetVersionList


def write_file(sheetVersionList):
    path = "../excel/workspace_test{}.xlsx".format(time.time())
    print(path)
    operateExcel.write_excel_info(sheetVersionList, path)


def bot_document_to_tree(file_path):

    wb = load_workbook(file_path)
    ws = wb[wb.sheetnames[2]]

    task_transfer_pattern = re.compile(r'【.*】')

    task_name = ''
    task_dict = dict()
    for i, row in enumerate(ws.values):
        task_logic = row[0]
        task_name = row[1] if row[1] else task_name
        task_stage = task_name+str(row[4])
        task_condition = row[5]
        task_wav_no = row[6]
        task_seat_response = row[7]
        task_simple_seat_response = row[8].replace('【faq答案】+', 'faq答案')
        task_label = '[' + row[9] + ']' if row[9] else ''
        task_response_label = '[' + row[10] + ']' if row[10] else ''
        task_break_label = row[16].replace('开场支持打断的标签：\n', '') if row[16] else ''

        if task_name not in task_dict:
            task_dict[task_name] = {
                'tree': dict(), # 以树结构保存的流程路线
                'tree_path': list(),
                'enter_simple_response': dict(),
                'simple_response': list(),
                'simple_response_to_response': dict(),
                'next_task': dict()
            }

        # 添加选择的简版话术
        if task_simple_seat_response not in task_dict[task_name]['simple_response']:
            task_dict[task_name]['simple_response'].append(task_simple_seat_response)
            task_dict[task_name]['simple_response_to_response'][task_simple_seat_response] = {
                'wav_no': task_wav_no,
                'response': task_seat_response,
                'label': task_label,
                'response_label': task_response_label,
            }


        # 构建bot树
        # 当节点中出现省略时，进行补充溯源
        if 'x' in task_stage and 'y' in task_stage and 'z' in task_stage:
            for x_num in task_stage.split('\n')[1].split('x=')[-1].split(','):
                for y_num in task_stage.split('\n')[2].split('y=')[-1].split(','):
                    for z_num in task_stage.split('\n')[3].split('z=')[-1].split(','):
                        for condition in task_dict[task_name]['tree']:
                            tree = task_dict[task_name]['tree'][condition]
                            tree.create_node(
                                task_condition,
                                task_stage.split('\n')[0].replace('x', x_num).replace('y', y_num).replace('z', z_num),
                                '.'.join(task_stage.split('\n')[0].replace('x', x_num).replace('y', y_num).replace('z', z_num).split('.')[:-1]),
                                # task_simple_seat_response,
                                task_wav_no if task_wav_no else task_simple_seat_response,
                            )
        elif 'x' in task_stage and 'y' in task_stage:
            for x_num in task_stage.split('\n')[1].split('x=')[-1].split(','):
                for y_num in task_stage.split('\n')[2].split('y=')[-1].split(','):
                    for condition in task_dict[task_name]['tree']:
                        tree = task_dict[task_name]['tree'][condition]
                        tree.create_node(
                            task_condition, task_stage.split('\n')[0].replace('x', x_num).replace('y', y_num),
                            '.'.join(task_stage.split('\n')[0].replace('x', x_num).replace('y', y_num).split('.')[:-1]),
                            # task_simple_seat_response,
                            task_wav_no if task_wav_no else task_simple_seat_response,
                        )
        elif 'x' in task_stage:
            for num in task_stage.split('\n')[1].split('x=')[-1].split(','):
                # for num in task_stage.replace(')', '').split('x=')[-1].split(','):
                for condition in task_dict[task_name]['tree']:
                    tree = task_dict[task_name]['tree'][condition]
                    tree.create_node(
                        task_condition, task_stage.split('\n')[0].replace('x', num),
                        '.'.join(task_stage.split('\n')[0].replace('x', num).split('.')[:-1]),
                        # task_simple_seat_response,
                        task_wav_no if task_wav_no else task_simple_seat_response,
                    )
        else:
            stage_level = task_stage.count('.')
            if stage_level == 0:
                tree = Tree()
                # tag=None（进入条件）, identifier=None（节点编号）, parent=None（上个节点编号）, data=None（动作，回复话术或者已完成任务）
                tree.create_node(task_condition, task_stage, None,
                                 # task_simple_seat_response,
                                 task_wav_no if task_wav_no else task_simple_seat_response,)
                task_dict[task_name]['tree'][task_condition] = tree

                task_dict[task_name]['enter_simple_response'][task_condition] = task_simple_seat_response

            else:
                for condition in task_dict[task_name]['tree']:
                    tree = task_dict[task_name]['tree'][condition]
                    tree.create_node(task_condition, task_stage, '.'.join(task_stage.split('.')[:-1]),
                                     # task_simple_seat_response,
                                     task_wav_no if task_wav_no else task_simple_seat_response,)

    all_num = 0
    # 每个子树获取所有到叶子节点的路径
    for task_name in task_dict:
        for condition in task_dict[task_name]['tree']:
            for paths in task_dict[task_name]['tree'][condition].paths_to_leaves():
                path_list = list()
                for path_id in paths:
                    path_list.append(task_dict[task_name]['tree'][condition].get_node(path_id).tag)
                    path_list.append(task_dict[task_name]['tree'][condition].get_node(path_id).data)

                # 添加路径
                task_dict[task_name]['tree_path'].append(path_list)

                # 添加到达其他任务的路径
                leave_data = task_transfer_pattern.search(task_dict[task_name]['tree'][condition].get_node(paths[-1]).data)
                if leave_data:
                    leave_data = leave_data.group().replace('【', '').replace('】', '')
                    if leave_data not in task_dict[task_name]['next_task'] or \
                        (leave_data in task_dict[task_name]['next_task'] and len(task_dict[task_name]['next_task'][leave_data]) > len(path_list)):

                        task_dict[task_name]['next_task'][leave_data] = path_list


        all_num += len(task_dict[task_name]['tree_path'])
        print(task_name)
        print(task_dict[task_name]['tree_path'])
        print(task_dict[task_name]['next_task'])

    print(all_num)

    # 从核身开场开始进行数据构建
    finish_paths_list = list()
    unfinish_paths_list = list()

    finish_paths_list.extend(task_dict['核身']['tree_path'])
    for next_task in task_dict['核身']['next_task']:
        unfinish_paths_list.append(
            task_dict['核身']['next_task'][next_task]
        )
    # print(finish_paths_list)
    # print(unfinish_paths_list)
    while unfinish_paths_list:
        paths_list = list()
        for path in tqdm.tqdm(unfinish_paths_list):
            task_name = task_transfer_pattern.search(path[-1]).group().replace('【', '').replace('】', '')
            for next_task_path in task_dict[task_name]['tree_path']:
                finish_path = copy.deepcopy(path[:-1])
                finish_path.extend(next_task_path[1:])
                if finish_path not in finish_paths_list:
                    finish_paths_list.append(finish_path)
                # print(finish_path)

            for next_task in task_dict[task_name]['next_task']:
                finish_path = copy.deepcopy(path[:-1])
                finish_path.extend(task_dict[task_name]['next_task'][next_task][1:])
                paths_list.append(finish_path)

        unfinish_paths_list = paths_list

    # print(finish_paths_list)
    # print(unfinish_paths_list)
    print(len(finish_paths_list))

    sheetVersionList = []
    test_path_list= list()
    for path in finish_paths_list:
        # 替换路径找到对应的录音编号
        if '【' in path[-1] and '】' in path[-1]:
            enter_condition = path[-1].split('】')[-1]
            task_name = task_transfer_pattern.search(path[-1]).group().replace('【', '').replace('】', '')
            if enter_condition and enter_condition in task_dict[task_name]['enter_simple_response']:
                simple_response = task_dict[task_name]['enter_simple_response'][enter_condition]
            else:
                simple_response = task_dict[task_name]['enter_simple_response']['首句']

            wav_no = task_dict[task_name]['simple_response_to_response'][simple_response]['wav_no']
            path[-1] = wav_no

        # 生成测试数据
        user_response = list()
        for i, row in enumerate(path[2:]):
            # 优化row
            if 'FAQ' in row:
                row = '什么平台'
            if row == '静音':
                row = '@@quiet@@'
            if '\n' in row:
                row = row.split('\n')[0]

            if i % 2 != 0:
                if ['', '', ','.join(user_response), row] not in test_path_list:
                    test_path_list.append(['', '', ','.join(user_response), row])
                    # print(path)
                    # print(','.join(user_response), row)
            else:
                user_response.append(row)

    for temp in test_path_list:
        operateExcel.define_excel_format_test("", "", temp[2], temp[3], "", sheetVersionList)

    wb = Workbook()
    ws = wb.active

    for paths in tqdm.tqdm(test_path_list):
        ws.append(paths)

    wb.save('./test_dialogue_data.xlsx')
    return sheetVersionList


if __name__ == '__main__':

    # buildDataByFile = BuildDataByFile()
    # buildDataByFile.buildData()
    # buildDataByFile = BuildDataByLLM()
    # buildDataByFile.buildData()
    buildDataByFile = BuildDataByFileTwo()
    buildDataByFile.buildData()
    pass
